<template>
  <view class="main">
    <u-sticky>
      <qualificationAddStep :step="2"/>
    </u-sticky>

    <view class="content">
      <u--form
          labelPosition="left"
          :model="merchantDetail"
          :rules="storeInfoModelRules"
          ref="storeInfoForm"
          labelWidth="87"
          :labelStyle="{fontSize:'26rpx', color: 'rgba(0, 0, 0, 0.7)', padding: '18rpx 0'}"
      >
        <view class="content-item">
          <view class="content-title">上传经营信息</view>
          <u-form-item label=" " prop="licenseAndIndustryLicensePhotoUpLoaded" ref="licenseAndIndustryLicenseItem" labelWidth="0"
            v-if="merchantDetail.merchantType != merchantTypeEnum.PERSON.id">
            <view class="upload u-flex u-row-between">
              <u-upload
                  ref="licensePhotoUpload"
                  :fileList="licensePhotoUrlList"
                  @afterRead="photoUploadAfterRead"
                  :name="photoTypeEnum.licensePhoto"
                  :maxCount="1"
                  :width="imgWidth"
                  :height="imgHeight"
                  :maxSize="maxSize"
                  @oversize="bannerOversize"
                  @delete="deletePhoto(photoTypeEnum.licensePhoto)"
              >
                <u--image :showLoading="true" :src="`${baseStaticFileUrl}/image/pages-qualification/license-photo.png`"
                          :width="imgWidth" :height="imgHeight"/>
              </u-upload>

              <u-upload
                  :fileList="industryLicensePhotoUrlList"
                  @afterRead="photoUploadAfterRead"
                  :name="photoTypeEnum.industryLicensePhoto"
                  :maxCount="1"
                  :width="imgWidth"
                  :height="imgHeight"
                  :maxSize="maxSize"
                  @oversize="bannerOversize"
                  @delete="deletePhoto(photoTypeEnum.industryLicensePhoto)"
                  v-if="merchantDetail.merchantType == merchantTypeEnum.LIMITED_COMPANY.id"
              >
                <u--image :showLoading="true" :src="`${baseStaticFileUrl}/image/pages-qualification/industry-license-photo.png`"
                          :width="imgWidth" :height="imgHeight"/>
              </u-upload>
            </view>
          </u-form-item>
          <u-form-item label="营业执照名称" prop="legalPerson" borderBottom ref="legalPersonItem"
                       v-if="merchantDetail.merchantType != merchantTypeEnum.PERSON.id">
            <u--input border="none" placeholder="请输入营业执照名称" inputAlign="left" clearable fontSize="13" maxlength="64"
                      v-model="merchantDetail.legalPerson"/>
          </u-form-item>
          <u-form-item label="统一社会信用代码" prop="bussAuthNum" borderBottom ref="bussAuthNumItem"
                       v-if="merchantDetail.merchantType != merchantTypeEnum.PERSON.id">
            <u--input border="none" type="text" placeholder="请输入统一社会信用代码" inputAlign="left" clearable fontSize="13" maxlength="18"
                      v-model="merchantDetail.bussAuthNum"/>
          </u-form-item>
          <u-form-item label="营业地区" prop="region" borderBottom ref="regionItem" rightIcon="" @click="openManageRegion()">
            <u--input border="none" placeholder="请选择营业地区" inputAlign="left" clearable fontSize="13" :disabled="true" disabledColor="#fff"
                      v-model="merchantDetail.region"/>
            <u-icon
                slot="right"
                name="arrow-right"
            ></u-icon>
          </u-form-item>
          <u-form-item label="详细地址" prop="address" borderBottom ref="addressItem">
            <u--textarea v-model="merchantDetail.address" placeholder="请输入详细地址" :autoHeight="true" border="none"
            maxlength="50" placeholderClass="textarea-placeholder"/>
          </u-form-item>
          <u-form-item label="商户收款简称" prop="merchantShortName" ref="merchantShortNameItem">
            <u--input border="none" placeholder="请输入商户收款简称" inputAlign="left" clearable fontSize="13" maxlength="32"
                      v-model="merchantDetail.merchantShortName"/>
          </u-form-item>
        </view>
      </u--form>
    </view>

    <view class="footer">
      <u-button type="primary" text="下一步" :customStyle="nextStepBtnCustomStyle" @click="submit()"></u-button>
    </view>

    <pick-manage-region ref="pickManageRegion" :pickerValueDefault="cityPickerValueDefault" @onConfirm="onConfirm"
                        themeColor="#007AFF"></pick-manage-region>

    <licensePhotoComponent ref="licensePhotoComponent"/>
  </view>
</template>

<script>
import licensePhotoComponent from '@/pages-qualification/base-info/license-photo';
import merchantDetail from '@/common/po/merchant-detail.ts'
import qualificationAddStep from '@/components/qualification-add-step/qualification-add-step';
export default {
  components: {
    qualificationAddStep,
    licensePhotoComponent
  },
  data() {
    return {
      baseStaticFileUrl: this.$configPath.staticFileUrl,
      qiNiuImgURL: this.$configPath.qiNiuImgURL,

      maxSize: 3 * 1024 * 1024,
      imgWidth: '330rpx',
      imgHeight: '234rpx',
      nextStepBtnCustomStyle: {
        width: '690rpx',
        height: '88rpx',
        borderRadius: '120px',
        color: '#fff',
        margin: '14rpx auto 0rpx',
      },
	    toUrl: '/pages-qualification/add/store-info',
      merchantDetail: merchantDetail,
      storeInfoModelRules: {
        'region': {
          type: 'string',
          required: true,
          message: '请选择营业地区',
          max: 30,
          min: 4,
          trigger: ['blur'],
        },
        'address': {
          type: 'string',
          required: true,
          message: '请输入详细地址',
          max: 50,
          min: 5,
          trigger: ['blur'],
        },
        'merchantShortName': [{
          type: 'string',
          required: true,
          message: '请输入商户收款简称',
          max: 20,
          min: 2,
          trigger: ['blur'],
        },{
			validator: (rule, value, callback) => {
				if(this.merchantDetail.merchantType == this.$merchantTypeEnum.PERSON.id){
					return /^(?!.*酒店)(?!.*网吧)(?!.*ktv).*$/gi.test(value)
				}else{
					return true;
				}
			},
			message: '个人商户简称不能包含“酒店”、“网吧”、“ktv”文字',
			// blur和change事件触发检验
			trigger: ['blur', 'change'],
		}],
      },

      cityPickerValueDefault: [0, 0, 0],

      licensePhotoUrlList: [],
      industryLicensePhotoUrlList: [],
      photoTypeEnum: {
        licensePhoto: 'licensePhoto',
        industryLicensePhoto: 'industryLicensePhoto',
      },

      merchantTypeEnum: this.$merchantTypeEnum,
      accountTypeEnum: this.$accountTypeEnum,
      merchantInfoUploadStateEnum: this.$merchantInfoUploadStateEnum,
    };
  },
  onReady() {
    this.$refs.storeInfoForm.setRules(this.storeInfoModelRules)
  },
  onShow(){},
  onLoad(){
    this.getUncommittedMerchantInfo();
    uni.$on('updateMerchantInfo-storeInfo', this.onStoreInfo)
  },
  onUnload(){
    uni.$emit('updateMerchantInfo-manageInfo', {
      data: this.merchantDetail
    })
  },
  methods: {
    onStoreInfo(e){
      this.updateUncommittedMerchantInfo(false, e.data)
      this.initData(e.data);
    },

    initData(data){
      this.merchantDetail = data;
      // console.log("this.merchantDetail", this.merchantDetail)

      if (this.merchantDetail.merchantType != this.merchantTypeEnum.PERSON.id){
        this.storeInfoModelRules['licenseAndIndustryLicensePhotoUpLoaded'] = {
          type: 'boolean',
          required: true,
          message: '请上传营业执照、开户许可证照片',
          validator: (rule, value, callback) => {
            return value == true;
          },
        };
        this.storeInfoModelRules['legalPerson'] = {
          type: 'string',
          required: true,
          message: '请输入营业执照名称',
          max: 64,
          min: 3,
          trigger: ['blur'],
        };
        this.storeInfoModelRules['bussAuthNum'] = {
          type: 'string',
          required: true,
          message: '请输入统一社会信用代码，由18位数字、字母组成',
          len: 18,
          trigger: ['blur'],
        };
      }

      // 营业执照
      if (!this.$u.test.isEmpty(this.merchantDetail.licensePhoto)){
        this.licensePhotoUrlList.length = 0;
        this.licensePhotoUrlList.push({
          status: 'success',
          message: '',
          url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.licensePhoto)
        })
      }

      // 开户许可证
      if (!this.$u.test.isEmpty(this.merchantDetail.industryLicensePhoto)){
        this.industryLicensePhotoUrlList.length = 0;
        this.industryLicensePhotoUrlList.push({
          status: 'success',
          message: '',
          url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.industryLicensePhoto)
        })
      }

      this.checkLicensePhotoAndIndustryLicensePhoto();
    },

    // 营业执照重新上传
    licensePhotoUploadAgain(){
      this.licensePhotoUrlList.splice(0, 1);
      this.$nextTick(() => {
        this.$refs.licensePhotoUpload.chooseFile()
      })
    },

    // 获取最近一次的记录
    getUncommittedMerchantInfo(){
      this.$api('merchant.getUncommittedMerchantInfo', null).then(res => {
        if (res.status == 0) {
          if (!this.$u.test.isEmpty(res.data)){
            this.initData(res.data);
          }
        }
      }).catch(() => {
        uni.hideLoading();
      })
    },

    // 更新记录
    updateUncommittedMerchantInfo(isNav, data){
		  var that = this;
      this.$api('merchant.updateUncommittedMerchantInfo', data).then(res => {
        if (res.status == 0) {
          if (isNav){
			      uni.hideLoading();
            uni.navigateTo({
			      	url: that.toUrl,
              fail: function(res) {
                getApp().err("跳转下一步失败:" + res.errMsg)
              }
            })
          }
        } else {
          getApp().err("信息提交不成功：" + res.msg)
        }
      }).catch((e) => {
		  getApp().err("更新失败：" + e)
        uni.hideLoading();
      })
    },

    openManageRegion(){
      this.$refs.pickManageRegion.open();
    },
    onConfirm(e) {
      console.log("e", e)
      this.merchantDetail.region = e.label;
      this.merchantDetail.provinceCode = e.provinceCode;
      this.merchantDetail.cityCode = e.cityCode;
      this.merchantDetail.districtCode = e.districtCode;

      this.regionValidateField();
    },

    submit() {
      try {
        this.$refs.storeInfoForm.validate().then(res => {
			    uni.showLoading();
          this.updateUncommittedMerchantInfo(true, this.merchantDetail);
        }).catch(error => {
          getApp().err('请按红色文字提示输入完整信息才能进行下一步')
        })
      } catch (e) {
        console.error(e.toString())
        getApp().err('提交不成功：' + e.toString())
      }
    },

    async photoUploadAfterRead(event) {
		uni.showLoading({
			title: '上传中',
			mask: true
		})
		// #ifndef H5
		let _this = this;
		if(event.file.size > 1024000){
			uni.compressImage({
				src: event.file.url,
				quality: 60,
				success: comRes => {
					_this.photoUploadAfterReadFun(event,comRes.tempFilePath);
				}
			})
		}else{
			this.photoUploadAfterReadFun(event,event.file.url);
		}
		// #endif
		
		// #ifdef H5
		this.photoUploadAfterReadFun(event,event.file.url);
		// #endif
      
    },
	async photoUploadAfterReadFun(event,fileUrl) {
		const item = {
			url: fileUrl,
			status: 'uploading',
			message: '上传中'
		  }

		  if (event.name == this.photoTypeEnum.licensePhoto){
			this.licensePhotoUrlList.push(item);

			await this.photoUploadFilePromise(fileUrl,  this.$photoTypeEnum.LICENSE_PHOTO).then((res) => {
			  this.merchantDetail.licensePhoto = res.data.picture;
			  this.merchantDetail.legalPerson = res.data.legalPerson;
			  this.merchantDetail.bussAuthNum = res.data.bussAuthNum;
			  this.merchantDetail.address = res.data.address;

			  const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
			  this.licensePhotoUrlList.splice(0, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: url
			  }))

			  this.checkLicensePhotoAndIndustryLicensePhoto(true);

			  // 上传成功，识别失败
			  if (this.merchantInfoUploadStateEnum.FAILURE_TO_IDENTIFY == res.status) {
				// 调起识别失败提示，并将刚上传的图片展示给他看
				this.$refs.licensePhotoComponent.showPopup(url);
			  }

			}).catch((err) => {
			  this.licensePhotoUrlList.splice(0, 1);
			})
		  } else if (event.name == this.photoTypeEnum.industryLicensePhoto){
			this.industryLicensePhotoUrlList.push(item);

			await this.photoUploadFilePromise(fileUrl, null).then((res) => {
			  this.merchantDetail.industryLicensePhoto = res.data.picture;

			  const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
			  this.industryLicensePhotoUrlList.splice(0, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: url
			  }))

			  this.checkLicensePhotoAndIndustryLicensePhoto(true);
			}).catch((err) => {
			  this.industryLicensePhotoUrlList.splice(0, 1);
			})
		  } else {
			uni.hideLoading();
			this.$helpers.toast("e.name有误");
			return
		  }
	},

    photoUploadFilePromise(fileUrl, photoType) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: this.$configPath.baseURL + '/api/merchant/merchantRegisterUploadByApplet',
          filePath: fileUrl,
          name: 'file',
          header: {
            Authorization: 'Bearer ' + this.$store.getters.GET_VALUE("GET_TOKEN")
          },
          timeout: 6000,
          formData: {
            photoType: photoType
          },
          success: (res) => {
            uni.hideLoading();
            let data = JSON.parse(res.data);
            if (this.merchantInfoUploadStateEnum.SUCCESS == data.status) {
              this.$helpers.toast("上传成功", "success");
              resolve(data);
            } else if (this.merchantInfoUploadStateEnum.FAILURE_TO_IDENTIFY == data.status){
              //上传成功，识别失败
              resolve(data);
            } else {
              reject(data)
              getApp().err("上传不成功，" + data.msg);
            }
          },
          fail: (res) => {
            uni.hideLoading();
            let errMsg = res.errMsg;
            if (uni.$u.test.contains(errMsg, 'timeout')) {
              errMsg = "请求超时，请重新上传";
            }
            getApp().err(errMsg);
            reject("请求超时，请重新上传")
          },
        });
      })
    },

    deletePhoto(photoType){
      try {
        if (photoType == this.photoTypeEnum.licensePhoto){
          this.merchantDetail.licensePhoto = "";
          this.merchantDetail.legalPerson = "";
          this.merchantDetail.bussAuthNum = "";
          this.merchantDetail.address = "";
          this.licensePhotoUrlList.splice(0, 1)
        } else if (photoType == this.photoTypeEnum.industryLicensePhoto){
          this.merchantDetail.industryLicensePhoto = "";
          this.industryLicensePhotoUrlList.splice(0, 1)
        } else {
          getApp().err("图片类型有误")
        }
        this.checkLicensePhotoAndIndustryLicensePhoto(true);
      } catch (e){
        console.error(e.toString())
        this.$helpers.toast("删除不成功");
      }
    },


    checkLicensePhotoAndIndustryLicensePhoto(checked){
      if (this.merchantDetail.merchantType == this.merchantTypeEnum.INDIVIDUAL_HOUSEHOLD.id){
        // 个体户资质时就判断营业执照即可
        if (!this.$u.test.isEmpty(this.merchantDetail.licensePhoto)){
          this.merchantDetail.licenseAndIndustryLicensePhotoUpLoaded = true;
        } else {
          this.merchantDetail.licenseAndIndustryLicensePhotoUpLoaded = false;
        }
      } else {
        // 公司资质对个人、对公
        if (!this.$u.test.isEmpty(this.merchantDetail.licensePhoto)
          && !this.$u.test.isEmpty(this.merchantDetail.industryLicensePhoto)
        ){
          this.merchantDetail.licenseAndIndustryLicensePhotoUpLoaded = true;
        } else {
          this.merchantDetail.licenseAndIndustryLicensePhotoUpLoaded = false;
        }
      }

      if (checked){
        this.licenseAndIndustryLicensePhotoValidateField();
        this.legalPersonValidateField();
        this.bussAuthNumValidateField();
      }
    },

    bannerOversize() {
      getApp().err("图片大小超限，最大3MB。如图片来自相册，建议使用直接拍摄");
    },

    licenseAndIndustryLicensePhotoValidateField(){
      this.$refs.storeInfoForm.validateField('licenseAndIndustryLicensePhotoUpLoaded', err => {
        // console.log("err", err)
      })
    },

    legalPersonValidateField(){
      this.$refs.storeInfoForm.validateField('legalPerson', err => {
        // console.log("err", err)
      })
    },

    bussAuthNumValidateField(){
      this.$refs.storeInfoForm.validateField('bussAuthNum', err => {
        // console.log("err", err)
      })
    },

    regionValidateField(){
      this.$refs.storeInfoForm.validateField('region', err => {
        // console.log("err", err)
      })
    },

    err(message){
      var _that = this;
      uni.showModal({
        title: '',
        content: message,
        success(res) {

        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>

.main{
  .content{

    .content-item{
      background-color: $uni-bg-color;
      margin-bottom: 20rpx;
      padding: 24rpx 30rpx;

      .content-title{
        color: rgb(13, 13, 13);
        font-size: 30rpx;
      }

      .upload{
        padding: 30rpx 0rpx 12rpx ;
      }
    }
  }

  .footer{
    width: 100%;
    margin-top: 94rpx;
    padding-bottom: 74rpx;
  }
}

/deep/ .u-upload__wrap__preview {
  margin: 0 8px 0px 0 !important;
}

/deep/ .u-textarea__field {
  color: #303133 !important;
  font-size: $f-sm !important;
}
</style>
